package com.yhao.controller.tx;

import com.google.gson.Gson;
import com.yhao.Dao.tx.IdentifyRecordRepository;
import com.yhao.Dao.tx.NewPersonRepository;
import com.yhao.bean.base.BaseResult;
import com.yhao.bean.tx.*;
import com.yhao.config.TencentYoutuConfig;
import com.yhao.utils.TokenUtil;
import com.yhao.utils.sign.Youtu;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @author yhao
 * @create 2017-11-08 17:05
 * 腾讯人脸识别api
 */

@RestController()
@RequestMapping("/qqyoutu")
public class TxYouTuController {

    @Autowired
    TencentYoutuConfig youtuConfig;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    NewPersonRepository newPersonRepository;

    @Autowired
    IdentifyRecordRepository recordRepository;

    @Autowired
    Youtu youtu;

    List<String> groupList;

    @PostConstruct
    void init() {
        groupList = new ArrayList<>();
        groupList.add("g1");
    }


    /**
     * 创建个体
     *
     * @param token
     * @param image
     * @return
     */
    @Transactional
    @PostMapping("/newperson")
    public NewPerson newPerson(@RequestParam(name = "token") String token, @RequestParam(name = "image") String image
            , @RequestParam(name = "name") String name) {
        NewPerson newPerson = new NewPerson();
        if (StringUtils.isEmpty(token)) {
            newPerson.setErrorMsg("token is null!");
            newPerson.setErrorCode(-1);
            return newPerson;
        }
        String userName = TokenUtil.getUserNameFromToken(token, redisTemplate);
        if (StringUtils.isEmpty(userName)) {
            newPerson.setErrorMsg("token is illegal!");
            newPerson.setErrorCode(-1);
            return newPerson;
        }
        if (image.getBytes().length >= 2 * 1024 * 1024) {
            newPerson.setErrorMsg("image is illegal,It can't be more than 2M!");
            newPerson.setErrorCode(-1);
            return newPerson;
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = youtu.NewPersonImage(image, userName, groupList, name);
            String json = jsonObject.toString();
            newPerson = new Gson().fromJson(json, NewPerson.class);
            if (newPerson.getErrorCode() == 0) {
                newPersonRepository.saveAndFlush(newPerson);
            } else {
                newPerson.setErrorMsg("create person failed,tx response is : " + newPerson.getErrorMsg() + " , code is :" + newPerson.getErrorCode());
                return newPerson;
            }
        } catch (Exception e) {
            newPerson.setErrorMsg("create person failed," + e.getMessage());
            newPerson.setErrorCode(-1);
            return newPerson;
        }

        return newPerson;
    }


    /**
     * 人脸识别（记录识别时间）
     */
    @Transactional
    @PostMapping("/faceIdentify")
    public FaceIdentify faceIdentify(@RequestParam(name = "token") String token, @RequestParam(name = "image") String image) {
        FaceIdentify faceIdentify = new FaceIdentify();
        if (StringUtils.isEmpty(token)) {
            faceIdentify.setErrorMsg("token is null!");
            faceIdentify.setErrorCode(-1);
            return faceIdentify;
        }
        String userName = TokenUtil.getUserNameFromToken(token, redisTemplate);
        if (StringUtils.isEmpty(userName)) {
            faceIdentify.setErrorMsg("token is illegal!");
            faceIdentify.setErrorCode(-1);
            return faceIdentify;
        }
        NewPerson newPerson = newPersonRepository.findByPersonId(userName);
        if (newPerson == null) {
            faceIdentify.setErrorMsg("person is null,maybe not create person!");
            faceIdentify.setErrorCode(-1);
            return faceIdentify;
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = youtu.FaceIdentifyImage(image, groupList.get(0));
            String json = jsonObject.toString();
            faceIdentify = new Gson().fromJson(json, FaceIdentify.class);
            // TODO: 2017/11/8 储存验证次数
            if (faceIdentify.getErrorCode() == 0) {
                IdentifyRecord identifyRecord = new IdentifyRecord();
                identifyRecord.setUserName(userName);
                identifyRecord.setArraySize(faceIdentify.getCandidates().size());
                recordRepository.save(identifyRecord);
            } else {
                faceIdentify.setErrorMsg("create person failed,tx response code is : " + faceIdentify.getErrorCode());
                return faceIdentify;
            }
        } catch (Exception e) {
            faceIdentify.setErrorMsg("create person failed," + e.getMessage());
            faceIdentify.setErrorCode(-1);
            return faceIdentify;
        }

        return faceIdentify;
    }

    /**
     * 查询识别记录
     */
    @Transactional
    @PostMapping("/getFIHistory")
    public ListFIRecord queryIdentifyRecord(@RequestParam(name = "token") String token) {
        ListFIRecord record = new ListFIRecord();
        if (StringUtils.isEmpty(token)) {
            record.setMassage("token is null!");
            record.setCode(-1);
            return record;
        }
        String userName = TokenUtil.getUserNameFromToken(token, redisTemplate);
        if (StringUtils.isEmpty(userName)) {
            record.setMassage("token is illegal!");
            record.setCode(-1);
            return record;
        }
        int time = recordRepository.countByUserName(userName);
        record.setTime(time);
        record.setCode(1);
        record.setMassage("ok");
        return record;
    }


    @PostMapping("/test")
    public BaseResult test(@RequestParam(name = "token") String token, @RequestParam("file") MultipartFile file, @RequestParam(name = "image") String image) {


        BaseResult baseResult = new BaseResult();

        baseResult.setMassage("test");
        String userName = TokenUtil.getUserNameFromToken(token, redisTemplate);
        Youtu faceYoutu = new Youtu(youtuConfig.getAppId(), youtuConfig.getSecretId(),
                youtuConfig.getSecretKey(), Youtu.API_YOUTU_END_POINT, "329431545");
        List<String> l = new ArrayList<>();
        l.add("test_group");
        JSONObject jsonObject = null;
        try {
//             jsonObject =  faceYoutu.NewPerson("classpath:11.jpg","test person id",l);

            // 获取文件名(包括后缀)
            String fileName = file.getOriginalFilename();
            //文件名只包含英文字母，数字，下划线和 .
            if (!fileName.matches("[0-9A-Za-z_.]*")) {
                // 获取文件的后缀名(包括 . )
                String suffixName = fileName.substring(fileName.lastIndexOf("."));
                // 解决中文问题，liunx下中文路径，图片显示问题
                fileName = new Date().getTime() + suffixName;
            }
            // 文件上传后的路径
            String filePath = "E://test//";
//            String filePath = "/home/img/";

            File dest = new File(filePath + fileName);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            jsonObject = faceYoutu.NewPersonFile(dest, "test_person_id", l);
            jsonObject = faceYoutu.NewPersonImage(image, "test_person_id1", l, "");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        String s = jsonObject.toString();
        return baseResult;
    }
}

